package com.huixin.zhang.common.core;

import com.alibaba.fastjson.JSONObject;

import com.huixin.zhang.common.bean.UploadResultBean;
import com.huixin.zhang.common.bean.code.ResultBean;
import com.huixin.zhang.common.utils.DateTimeUtils;
import com.huixin.zhang.common.utils.UploadUtils;
import com.huixin.zhang.persistence.entity.BaseUser;
import com.huixin.zhang.service.BaseUserService;
import com.huixin.zhang.common.utils.SecurityUtils;
import com.huixin.zhang.common.config.PlatFormProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

public class GenericController {
	public static final String INDEX = "index";
	public static final String CREATE = "create";
	public static final String UPDATE = "update";
	public static final String DETAIL = "detail";
	public static final String QUERY = "query";
	public static final String DELETE = "delete";

	@Resource
	protected BaseUserService baseUserService;
	@Resource
	protected PlatFormProperties platFormProperties;

	protected ResultBean getOnline() {
		String username = SecurityUtils.getUsername();
		if(StringUtils.isBlank(username)){
			return ResultBean.timeout();
		}
		BaseUser merUser = baseUserService.findByLoginName(username);
		if(merUser == null){
			return ResultBean.notfund();
		}
		return ResultBean.success(merUser);
	}

	protected void initBetweenDateTime(JSONObject params){
		initBetweenDateTime(params, true);
	}

	protected void initBetweenDateTime(JSONObject params, boolean hasCurrent){
		String startDate = params.getString("startDate");
		if (StringUtils.isNotBlank(startDate)) {
			params.put("startDate", startDate + " 00:00:00");
		}
		String endDate = params.getString("endDate");
		if (StringUtils.isNotBlank(endDate)) {
			params.put("endDate", endDate + " 23:59:59");
		}

		if(hasCurrent && (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate))){
			Date now = new Date();
			if(StringUtils.isNotBlank(startDate)){
				params.put("startDate", DateTimeUtils.dateFormate(now, "yyyy-MM-dd 00:00:00"));
			}
			if(StringUtils.isNotBlank(endDate)) {
				params.put("endDate", DateTimeUtils.dateFormate(now, "yyyy-MM-dd 23:59:59"));
			}
		}
	}

	protected UploadResultBean upload(String destFilePath, MultipartFile file) throws IOException {
		return UploadUtils.upload(platFormProperties.getUploadPath(), destFilePath, file);
	}

	protected UploadResultBean uploadTemp(MultipartFile file) throws IOException {
		return UploadUtils.upload(platFormProperties.getTempPath(), null, file);
	}
}
